package com.myh.exam.controller;

import com.myh.exam.dto.User;
import com.myh.exam.service.UserService;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/editUser")
public class EditUserServlet extends HttpServlet {

    private UserService userService = new UserService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        Integer id = null;
        if (StringUtils.isNotEmpty(req.getParameter("id"))) {
            id = Integer.valueOf(req.getParameter("id"));
        }
        String name = req.getParameter("name");
        String nickName = req.getParameter("nickName");
        String passwd = req.getParameter("passwd");
        String regExp = "^[^0-9][\\w_]{5,9}$";
        if (!name.matches(regExp)) {
            req.setAttribute("name", name);
            req.setAttribute("nickName", nickName);
            req.setAttribute("passwd", passwd);
            req.setAttribute("msg", "用户名不合法，请重新输入");
            req.getRequestDispatcher("editUser.jsp").forward(req, resp);
            return;
        }
        int result = 0;
        if (id == null || id == 0) {
            result = userService.addUser(new User(name, nickName, passwd));
        } else {
            result = userService.updateUser(new User(id, name, nickName, passwd));
        }
        if (result > 0) {
            //1.获取列表数据
            List<User> userList = userService.selectUserList(new User(), 0, 100);
            //2.将数据传给下一个页面
            req.setAttribute("list", userList);
            req.getRequestDispatcher("listUser.jsp").forward(req, resp);
        } else {
            req.getRequestDispatcher("error.jsp").forward(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
